﻿using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Singer.UnitTestWeb.Domain.Users;
using Singer.UnitTestWeb.Models.Dtos;

namespace Singer.UnitTestWeb.Controllers
{
    public class FreeSqlController : ApiControllerBase
    {
        IFreeSql _freeSql;
        IUserFreeSqlRepository _userFreeSqlRepository;
        public FreeSqlController(
            IServiceProvider serviceProvider,
            IUserFreeSqlRepository userFreeSqlRepository) : base(serviceProvider)
        {
            _userFreeSqlRepository = userFreeSqlRepository;
            _freeSql = userFreeSqlRepository.Orm;
        }


        [HttpGet]
        public Task<List<UserDto>> GetUserListAsync()
        {
            return _freeSql.Select<User>().ToListAsync<UserDto>();
        }

        [HttpGet]
        public Task<User> GetAsync(int id)
        {
            return _freeSql.Select<User>().Where(x => x.Id == id).FirstAsync();
        }

        [HttpPost]
        public async Task AddAsync([FromBody] UserDto dto)
        {
            var user = new User(dto.Account, dto.Name, dto.Age, dto.Password);
            var a = User;
            var b = UserContext;
            //await _freeSql.Insert<User>().ExecuteAffrowsAsync();
            user.Id = await _freeSql.Insert(user).ExecuteIdentityAsync();
        }

        [HttpPost]
        public async Task EditAsync([FromBody] UserDto dto)
        {
            //1.直接通过条件改
            await _freeSql.Update<User>()
                .Set(x => x.Name, dto.Name)
                .Set(x => x.Account, dto.Account)
                .Where(x => x.Id == dto.Id)
                .ExecuteAffrowsAsync();
            //2.先查再改
            //var user = await _freeSql.Select<User>().Where(x => x.Id == dto.Id).FirstAsync();
            //user.Name = dto.Name;
            //user.Account = dto.Account;
            //await _freeSql.Update<User>().SetSource(user).ExecuteAffrowsAsync();

            //3.根据Dto修改 (需要忽略id主键  IgnoreColumns 要在 SetDto 之前)
            //await _freeSql.Update<User>().Where(x => x.Id == dto.Id).IgnoreColumns(x => x.Id).SetDto(dto).ExecuteAffrowsAsync();
        }


        [HttpGet]
        public async Task SolftDeleteAsync()
        {
            string[] deleteAccounts = new string[] { "aaa", "bbb", "ccc" };

            //1.删除单个实体，先查再删
            User? user = await _userFreeSqlRepository.GetAsync(x => x.Account == "aaa");
            if (user != null)
                await _userFreeSqlRepository.DeleteAsync(user);

            //2.根据实体集合批量删除，先查再删
            //List<User> users = await _userFreeSqlRepository.Where(x => deleteAccounts.Contains(x.Account)).ToListAsync();
            //await _userFreeSqlRepository.DeleteAsync(users);

            //3.根据表达式条件删除
            await _userFreeSqlRepository.DeleteAsync(x => x.Account == "ccc");

        }
    }
}
